#pragma once
#include "Comm.hpp"


//初始化创建管道
class Init
{
public:
    Init()
    {
        umask(0);
        int n = ::mkfifo(filename.c_str(), fmode);
        if (n < 0)
        {
            std::cerr << "mkfifo error" << std::endl;
            return;
        }
        std::cout << "mkfifo success" << std::endl;
        sleep(5);
    }

    ~Init()
    {
        int flag = ::unlink(filename.c_str());
        if (flag < 0)
        {
            std::cerr << "unlink error" << std::endl;
            return;
        }
        std::cout << "unlink success" << std::endl;
    }
};

Init it;

class Server
{
public:
    Server() : _fd(defaultfd)
    {
        _fd = OpenPipeRead();//如果读端打开文件时，写端还没打开，读端就会阻塞
        if(_fd<0) exit(0);
    }


    //读端
    ssize_t ReadPipe(std::string *out)
    {
        char buffer[readsize];
        ssize_t n = ::read(_fd, buffer, readsize - 1);
        if (n > 0)
        {
            buffer[n] = 0;
            *out = buffer;
        }
        return n;
    }


    ~Server()
    {
        ClosePipe();
    }

private:
    int _fd;
};